import { useEffect, useRef, useState } from "react";

const flower_scr = 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4'

export default function RefCounter() {
    let ref = useRef<number>(0)
    const [count, setCount] = useState<number>(ref.current)

    function handleClick() {
        ref.current = ref.current + 1
        setCount(ref.current)
    }

    function reset() {
        ref.current = 0
        setCount(0)
    }

    return (
        <div>
            <label >{count}</label>
            <br />
            <button onClick={handleClick}> add </button>
            <button onClick={reset}> reset </button>
        </div>
    )
}

interface VideoProps {
    src: string
    isPlaying: boolean
    style: React.CSSProperties
}

function VideoPlayer(props: VideoProps) {
    const ref = useRef<HTMLVideoElement>(null)

    useEffect(() => {
        if (props.isPlaying) {
            ref.current?.play();
        } else {
            ref.current?.pause();
        }
    }, [props.isPlaying]);

    return <video ref={ref} src={props.src} loop playsInline style={props.style} />
}

export function PlayerApp() {
    const [isPlaying, setIsPlaying] = useState<boolean>(false)
    const style: React.CSSProperties = {
        width: 250
    }
    return (
        <div style={style}>
            <button onClick={() => setIsPlaying(!isPlaying)}>{isPlaying ? '暂停' : '播放'}</button>
            <br />
            <VideoPlayer style={style} isPlaying={isPlaying} src={flower_scr} />
        </div>
    )
}